package com.integrationpath.mengine.webapp.servlet;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.integrationpath.mengine.service.ArticleManager;
import com.integrationpath.mengine.service.impl.ArticleManagerImpl;

public class DisplayImageServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
		

        ArticleManager articleManager = (ArticleManager) getSpringContext(request).getBean("articleManagerNew");
        byte[] thumbnail = articleManager.getArticleThumbnail(new Long(request.getParameter("id")));
        if(thumbnail != null) {
        	ServletOutputStream out = response.getOutputStream();
			response.setContentType("image/gif");
			InputStream in = new ByteArrayInputStream(thumbnail);
			int length = (int) thumbnail.length;
	
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
	
			while ((length = in.read(buffer)) != -1) {
				out.write(buffer, 0, length);
			}
        
		in.close();
		out.flush();
        }
	}

	private WebApplicationContext getSpringContext(HttpServletRequest request) {
		return WebApplicationContextUtils.getWebApplicationContext(request
				.getSession().getServletContext());
	}
}
